package cn.wolfcode.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.EmployeeRole;
import cn.wolfcode.domain.Role;
import cn.wolfcode.query.EmployeeQueryObject;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jishushen
 * @create 2021-02-19 13:59
 * 系统管理之员工管理
 */
@Api(value = "员工资源",description = "员工资源控制器")
@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IEmployeeRoleService employeeRoleService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"employee:list","员工列表"},logical = Logical.OR)
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model){
        PageInfo<Employee> pr =  employeeService.listpage(qo);
        List<Department> list = departmentService.listAll();
        model.addAttribute("pageInfo",pr);
        model.addAttribute("depts",list);
        return "employee/list";
    }

    @GetMapping("/input")
    @RequiresPermissions(value = {"employee:input","员工编辑"},logical = Logical.OR)
    public String input(Model model,Long id){
        List<Department> list = departmentService.listAll();
        List<Role> roles = roleService.selectAll();
        model.addAttribute("depts",list);
        model.addAttribute("roles",roles);
        if (id != null){
            //修改
            Employee employee = employeeService.selectByPrimaryKey(id);
            List<EmployeeRole> employeeRoleList = employeeRoleService.selectByEmployee(id);
            List<Role> roleList = new ArrayList<>();
            for (EmployeeRole employeeRole : employeeRoleList) {
                Role role = roleService.selectByPrimaryKey(employeeRole.getRole_id());
                roleList.add(role);
            }
            model.addAttribute("employee",employee);
            model.addAttribute("roleList",roleList);
        }
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids){
        try {
            if (employee.getId() != null){
                //修改
                employeeService.updateByPrimaryKey(employee);
                //判断是不是超级管理员
                if (!employee.isAdmin()){
                    //不是超级管理员

                    //先删除原有的employee_role表中的对应关系
                    employeeRoleService.delete(employee.getId());
                    //再判断ids是否有值
                    if (ids != null){
                        //ids不为空，则重新在employee_role表中添加对应关系
                        for (Long id : ids) {
                            employeeRoleService.insert(new EmployeeRole(employee.getId(),id));
                        }
                    }
                }

            }else {
                //对新增的员工密码进行加密,把用户名当做盐
                Md5Hash hash  = new Md5Hash(employee.getPassword(),employee.getName());
                employee.setPassword(hash.toString());

                //新增,保存到数据库
                employeeService.insert(employee);
                Long eId = employee.getId();
                //判空
                if (ids != null){
                    for (Long id : ids) {
                        employeeRoleService.insert(new EmployeeRole(eId,id));
                    }
                }
            }

            return new JsonResult(true,"操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    @GetMapping("/delete")
    public String delete(Long id){
        employeeService.deleteByPrimaryKey(id);
        employeeRoleService.delete(id);
        return "redirect:/employee/list.do";
    }


    //批量删除
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids){
        try {
            //employee表进行批量删除
            employeeService.batchDelete(ids);

            //employee_role表也进行批量删除

            for (Long id : ids) {
                employeeRoleService.delete(id);
            }
            return new JsonResult(true,"批量删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"批量删除失败！");
        }

    }

    //验证用户名是否存在，存在不添加，不存在添加
    @RequestMapping("/checkName")
    @ResponseBody
    //由于前端表单验证在验证用户名的内容是否合法，所有会自动将name对应的值传递到后台
    public Map<String,Boolean> checkName(String name){
        Employee employee = null;

        try {
            employee = employeeService.selectByName(name);
        } catch (Exception e) {
            e.printStackTrace();
            employee = null;
        }
        Map<String,Boolean> map = new HashMap<>();
        //如果 employee等于null,那么说明数据库中没有，可以添加。否则反之。
        map.put("valid",employee == null);
        return map;
    }

    //导出(下载)
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //创建excel文件
        Workbook wb = employeeService.exportXls();
        wb.write(response.getOutputStream());
    }

    //下载模板
    @RequestMapping("/employeeImport")
    public void employeeImport(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //创建excel文件
        Workbook wb = employeeService.employeeImport();
        wb.write(response.getOutputStream());
    }

    //导入到数据库(上传)
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file){
        try {
            employeeService.importXls(file);
            return new JsonResult(true,"导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"导入失败");
        }

    }
}
